package cn.sylinx.hbatis.plugin.ehcache;

import java.io.InputStream;
import java.net.URL;

import cn.sylinx.hbatis.db.cache.CacheKitManager;
import cn.sylinx.hbatis.plugin.IPlugin;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.Configuration;

/**
 * ehcache支持
 * 
 * @author han
 *
 */
public class EhcachePlugin implements IPlugin {

	private static CacheManager cacheManager;
	private String configurationFileName;
	private URL configurationFileURL;
	private InputStream inputStream;
	private Configuration configuration;

	public void setConfigurationFileName(String configurationFileName) {
		this.configurationFileName = configurationFileName;
	}

	public void setConfigurationFileURL(URL configurationFileURL) {
		this.configurationFileURL = configurationFileURL;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}

	public EhcachePlugin() {

	}

	public EhcachePlugin(CacheManager cacheManager) {
		EhcachePlugin.cacheManager = cacheManager;
	}

	public EhcachePlugin(String configurationFileName) {
		this.configurationFileName = configurationFileName;
	}

	public EhcachePlugin(URL configurationFileURL) {
		this.configurationFileURL = configurationFileURL;
	}

	public EhcachePlugin(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public EhcachePlugin(Configuration configuration) {
		this.configuration = configuration;
	}

	public boolean start(Object... objects) {
		createCacheManager();
		CacheKitManager.set(CacheKit.INSTANCE.init(cacheManager));
		return true;
	}

	private void createCacheManager() {
		if (cacheManager != null)
			return;

		if (configurationFileName != null) {
			cacheManager = CacheManager.create(configurationFileName);
			return;
		}

		if (configurationFileURL != null) {
			cacheManager = CacheManager.create(configurationFileURL);
			return;
		}

		if (inputStream != null) {
			cacheManager = CacheManager.create(inputStream);
			return;
		}

		if (configuration != null) {
			cacheManager = CacheManager.create(configuration);
			return;
		}

		cacheManager = CacheManager.create();
	}

	public boolean stop() {
		cacheManager.shutdown();
		CacheKit.INSTANCE.destory();
		cacheManager = null;
		return true;
	}
}
